package com.taotao.springmvc.ext;


import com.taotao.springmvc.init.TaoTaoMappingRegistContainer;
import com.taotao.springmvc.init.TaoTaoMappingRegistration;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;


@WebServlet("*.do")
public class TaoTaoDispatcherServlet implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        PrintWriter writer = httpServletResponse.getWriter();
        //获取客户端访问url
        String requestURI = httpServletRequest.getRequestURI();
        try {
            //2 在根据改url 从映射的map 集合查找对应的 handler 和方法

            TaoTaoMappingRegistration mayiktMappingRegistration
                    = TaoTaoMappingRegistContainer.getRegistUrl().get(requestURI);
            if (mayiktMappingRegistration == null) {
                //没有对应的 映射handler和方法；
                httpServletResponse.setStatus(404);
                writer.println("404");
                return;
            }
            //利用反射机制调用handler 和方法
            Object handler = mayiktMappingRegistration.getHandler();
            Method handlerMethod = mayiktMappingRegistration.getHandlerMethod();
            //调用映射方法
            Object result = handlerMethod.invoke(handler, null);
            TaoTaoResponseBody taoTaoResponseBody = handlerMethod.getDeclaredAnnotation(TaoTaoResponseBody.class);
                 if(taoTaoResponseBody !=null){
                     writer.println(result);//返回json 数据
                 }else {
                     //页面跳转
                     httpServletRequest.getRequestDispatcher((String) result).forward(httpServletRequest,httpServletResponse);
                 }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}